const { pathToAliPrefix } = require('../utils/utils')
const path = require("path");
const OSS = require("ali-oss");

async function handleDel(client, name) {
    try {
        const results = await client.delete(name);
        return results;
    } catch (error) {
        error.failObjectName = name;
        return error;
    }
}

module.exports = async function ({ config, ossName, type = 'file' }) {
    if (!ossName || ossName === '/' || ossName === './') return;
    const ossConfig = config ? config : this.getOssConfig()
    const client = new OSS(ossConfig);
    if (type === 'file') {
        const result = await handleDel(client, ossName)
        if (result?.failObjectName) {
            console.log({ success: 0, fails: [result?.failObjectName] })
            return { success: 0, fails: [result?.failObjectName] }
        }
        console.log({ success: 1, fails: [] })
        return { success: 1, fails: [] };
    }
    if (type === 'dir') {
        const prefix = pathToAliPrefix(ossName)
        const list = await client.listV2({
            prefix
        })
        list.objects = list.objects || [];
        const results = await Promise.all(list.objects.map((v) => handleDel(client, v.name)));
        let success = 0
        const fails = []
        results?.forEach(item => {
            if (!item?.failObjectName) success++;
            else {
                fails.push(item?.failObjectName)
            }
        })
        console.log({ success, fails })
        return { success, fails }
    }

}